package main

import (
	"books/models"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

func (a *App) GetLoans(name, user string, is_return int) []models.Loan {
	loans, err := models.GetLoans(name, user, is_return)
	if err != nil {
		runtime.EventsEmit(a.ctx, "error", err.Error())

		return nil
	}

	return loans
}

func (a *App) CreateLoan(user_id uint64, book_id uint64, should_return_date uint64) error {
	loan := models.Loan{
		UserID:           user_id,
		BookID:           book_id,
		ShouldReturnDate: should_return_date,
	}

	err := loan.CreateLoan()
	if err != nil {
		return err
	}

	book, err := models.GetBook(book_id)

	if err != nil {
		return err
	}

	book.Available = book.Available - 1
	err = book.Save()
	if err != nil {
		return err
	}

	user, err := models.GetUser(user_id)

	if err != nil {
		return err
	}

	user.BorrowCount = user.BorrowCount + 1

	err = user.Save()

	if err != nil {
		return err
	}

	return nil
}

func (a *App) ReturnBook(id uint64) error {
	loan, err := models.GetLoan(id)
	if err != nil {
		return err
	}
	book, err := models.GetBook(loan.BookID)
	if err != nil {
		return err
	}
	book.Available = book.Available + 1
	err = book.Save()
	if err != nil {
		return err
	}
	err = models.Return(id)

	if err != nil {
		return err
	}

	return nil
}
